﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Fis.Win.Utils;
using Agile.Engine.Utils;
using System.Text.RegularExpressions; 

namespace Fis.Win.Forms
{
    public partial class InitializeForm : BaseForm
    {
        DataTable AccountSource = CacheContext.GetCache("TACCOUNT");
        DataTable LowerAccountSource = CacheContext.LowerAccountCache();
        DataTable BookSource = CacheContext.GetCache("TBOOK");
        DataTable RestSource = CacheContext.GetCache("TREST");
        public InitializeForm()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            DataTable BillSource = ViewModel["BillData"] as DataTable;
            //初始化凭证检测
            DateTime BOOKSTARTIME = DateTime.Parse(BookSource.Rows[0]["FBOOKSTARTIME"].ToString());
            var BillSourceRow = BillSource.Select(string.Format("FENTERDATE>= '{0}' and FENTERDATE<'{1}'",
                DateTime.Parse(string.Format("{0}-{1}-1 00:00:00", BOOKSTARTIME.Year, 1)).AddYears(-1), BOOKSTARTIME));
            if (BillSourceRow.Length != 0)
            {
                CheckBill(BillSourceRow.CopyToDataTable());
            }
            else
            {
                //报消息：没有初始凭证，是否继续
            }
            CheckBill(BillSource);
            //初始化科目余额表
            InitializeRest(BillSource);
        }

        private void CheckBill(DataTable TempBillSource)
        {
            var ErrorBillCode = (string)null;
            var a = (string)null;
            for (int i = 0; i < TempBillSource.Rows.Count; i = i + 1)
            {
                a = CheckBillDetail(TempBillSource, i);
                if (!StringUtils.IsEmpty(a))
                {
                    if (StringUtils.IsEmpty(ErrorBillCode))
                        ErrorBillCode = string.Format("'{0}'", a);
                    else
                        ErrorBillCode += string.Format(",'{0}'", a);
                }
            }
            if (!StringUtils.IsEmpty(ErrorBillCode))
            {
                //报消息：初始凭证有误，请修改后，重新结束初始化
                System.Collections.Hashtable model = new System.Collections.Hashtable();
                model["filter0"] = string.Format("and m.SID in ({0}) ",ErrorBillCode);
                model["filter1"] = "";
                UIManager.ShowList<Forms.BillListForm>("BillListViewProvider", model);
            }
            return;
        }

        private string CheckBillDetail(DataTable TempBillSource, int i)
        {
            string[] Key = new string[2];
            Key[0] = TempBillSource.Rows[i]["SID"].ToString();
            Key[1] = TempBillSource.Rows[i]["FACCOUNTCODE"].ToString();
            var FHSVALUE = TempBillSource.Rows[i]["FHSVALUE"].ToString();
            if (StringUtils.IsEmpty(Key[1].ToString()))
                return Key[0].ToString();
            var AccountSourceRows = AccountSource.Select(string.Format("SID='{0}'", Key[1].ToString()));
            if (AccountSourceRows.Length == 0)
                return Key[0].ToString();
            var TempAccountSource = AccountSourceRows.CopyToDataTable();
            if (LowerAccountSource.Select(string.Format("SID='{0}'", Key[1].ToString())).Length == 0)
                return Key[0].ToString();
            if (StringUtils.IsEmpty(TempBillSource.Rows[i]["FEXPLANATION"].ToString()))
                return Key[0].ToString();
            if (StringUtils.IsEmpty(TempBillSource.Rows[i]["FDEBITAMOUNT"].ToString()) &&
                StringUtils.IsEmpty(TempBillSource.Rows[i]["FCREDITAMOUNT"].ToString()))
                return Key[0].ToString();
            if (TempAccountSource.Rows[0]["FISFZHS"].ToString() == "1")
            {
                if (TempAccountSource.Rows[0]["FWBHS"].ToString() != "0")
                {
                    if (StringUtils.IsEmpty(TempBillSource.Rows[i]["FCURRENCYDEBIT"].ToString()) &&
                    StringUtils.IsEmpty(TempBillSource.Rows[i]["FCURRENCYCREDIT"].ToString()))
                        return Key[0].ToString();
                    if (StringUtils.IsEmpty(TempBillSource.Rows[i]["FRATE"].ToString()))
                        return Key[0].ToString();
                }
                if (TempAccountSource.Rows[0]["FUNIT"].ToString() == "1")
                {
                    if (StringUtils.IsEmpty(TempBillSource.Rows[i]["FQUANTITYDEBIT"].ToString()) &&
                        StringUtils.IsEmpty(TempBillSource.Rows[i]["FQUANTITYCREDIT"].ToString()))
                        return Key[0].ToString();
                    if (StringUtils.IsEmpty(TempBillSource.Rows[i]["FUNITPRICE"].ToString()))
                        return Key[0].ToString();
                }
                if (!StringUtils.IsEmpty(TempAccountSource.Rows[0]["FFZHS"].ToString()))
                {
                    if (StringUtils.IsEmpty(TempBillSource.Rows[i]["FHSVALUE"].ToString()))
                        return Key[0].ToString();
                }
            }
            return "";
        }

        private void InitializeRest(DataTable BillSource)
        {
            DateTime BOOKSTARTIME = DateTime.Parse(BookSource.Rows[0]["FBOOKSTARTIME"].ToString());
            var StarTime = DateTime.Parse(string.Format("{0}-{1}-1 00:00:00", BOOKSTARTIME.Year, 1)).AddYears(-1);
            var EndTime = DateTime.Parse(string.Format("{0}-{1}-1 00:00:00", BOOKSTARTIME.Year, 1));
            var BillSourceRow = (DataRow[])null;
            var a = 0;
            for (int i = 0; i < BOOKSTARTIME.Month; i = i + 1)
            {
                if (i != 0)
                {
                    StarTime = DateTime.Parse(string.Format("{0}-{1}-1 00:00:00", BOOKSTARTIME.Year, i));
                    EndTime = StarTime.AddMonths(1);
                }
                BillSourceRow = BillSource.Select(string.Format("FENTERDATE>= '{0}' and FENTERDATE<'{1}'", StarTime, EndTime));
                if (BillSourceRow.Length != 0)
                {
                    AccountRate(BillSourceRow.CopyToDataTable(), i);
                }
                else
                {
                    AccountRate(null, i);
                }
                if (a == 0)
                {
                    if (int.Parse(RestSource.Compute("count(FDEBITAMOUNTQM)", string.Format("FDEBITAMOUNTQM<>0.000000 and  FRANGE='{0}'", i)).ToString()) + 
                            int.Parse(RestSource.Compute("count(FCREDITAMOUNTQM)", string.Format("FCREDITAMOUNTQM<>0.000000 and  FRANGE='{0}'", i)).ToString()) == 0)
                    {
                        RestSource.Rows.Clear();
                    }
                    else
                    {
                        a = 1;
                    }
                }
                //报消息：i月科目余额表不平，请调整后重新结束初始化。
                if (NulltoDecimal(RestSource.Compute("sum(FDEBITAMOUNTQM)", string.Format("FRANGE='{0}'", i)).ToString()) !=
                       NulltoDecimal(RestSource.Compute("sum(FCREDITAMOUNTQM)", string.Format("FRANGE='{0}'", i)).ToString()))
                {

                }
            }
        }

        private void AccountRate(DataTable TempBillSource, int Range)
        {
            string[] Key = new string[4];
            for (int i = 0; i < AccountSource.Rows.Count; i = i + 1)
            {
                Key[0] = AccountSource.Rows[i]["SID"].ToString();
                Key[1] = AccountSource.Rows[i]["FCODE"].ToString();
                Key[2] = string.Format("'{0}'", string.Join("','",
                    (from a in AccountSource.Select(string.Format("FCODE like '{0}%'", Key[1].ToString())) select a["SID"].ToString()).ToArray()));
                Key[3] = AccountSource.Rows[i]["FJD"].ToString();
                DataRow TempRow = RestSource.NewRow();
                TempRow["FACCCODE"] = Key[0].ToString();
                TempRow["FRANGE"] = Range.ToString();
                //初始化起初余额
                TempRow["FDEBITAMOUNTQC"] = decimal.Parse("0.000000");
                TempRow["FCREDITAMOUNTQC"] = decimal.Parse("0.000000");
                TempRow["FCURRENCYDEBITQC"] = decimal.Parse("0.000000");
                TempRow["FCURRENCYCREDITQC"] = decimal.Parse("0.000000");
                TempRow["FQUANTITYDEBITQC"] = decimal.Parse("0.000000");
                TempRow["FQUANTITYCREDITQC"] = decimal.Parse("0.000000");
                //初始化本期余额
                TempRow["FDEBITAMOUNTBQ"] = decimal.Parse("0.000000");
                TempRow["FCREDITAMOUNTBQ"] = decimal.Parse("0.000000");
                TempRow["FCURRENCYDEBITBQ"] = decimal.Parse("0.000000");
                TempRow["FCURRENCYCREDITBQ"] = decimal.Parse("0.000000");
                TempRow["FQUANTITYDEBITBQ"] = decimal.Parse("0.000000");
                TempRow["FQUANTITYCREDITBQ"] = decimal.Parse("0.000000");
                //初始化期末余额
                TempRow["FDEBITAMOUNTQM"] = decimal.Parse("0.000000");
                TempRow["FCREDITAMOUNTQM"] = decimal.Parse("0.000000");
                TempRow["FCURRENCYDEBITQM"] = decimal.Parse("0.000000");
                TempRow["FCURRENCYCREDITQM"] = decimal.Parse("0.000000");
                TempRow["FQUANTITYDEBITQM"] = decimal.Parse("0.000000");
                TempRow["FQUANTITYCREDITQM"] = decimal.Parse("0.000000");
                if (Range != 0)
                {
                    var RestRow = RestSource.Select(string.Format("FACCCODE='{0}' and FRANGE={1}", Key[0].ToString(), (Range - 1).ToString()));
                    if (RestRow.Length != 0)
                    {
                        var TempRest = RestRow.CopyToDataTable();
                        TempRow["FDEBITAMOUNTQC"] = TempRest.Rows[0]["FDEBITAMOUNTQM"];
                        TempRow["FCREDITAMOUNTQC"] = TempRest.Rows[0]["FCREDITAMOUNTQM"];
                        TempRow["FCURRENCYDEBITQC"] = TempRest.Rows[0]["FCURRENCYDEBITQM"];
                        TempRow["FCURRENCYCREDITQC"] = TempRest.Rows[0]["FCURRENCYCREDITQM"];
                        TempRow["FQUANTITYDEBITQC"] = TempRest.Rows[0]["FQUANTITYDEBITQM"];
                        TempRow["FQUANTITYCREDITQC"] = TempRest.Rows[0]["FQUANTITYCREDITQM"];
                    }
                }
                if (TempBillSource != null)
                {
                    var a = string.Format("FACCOUNTCODE in ({0})", Key[2].ToString());
                    TempRow["FDEBITAMOUNTBQ"] = NulltoDecimal(TempBillSource.Compute("sum(FDEBITAMOUNT)", a).ToString());
                    TempRow["FCREDITAMOUNTBQ"] = NulltoDecimal(TempBillSource.Compute("sum(FCREDITAMOUNT)", a).ToString());
                    TempRow["FCURRENCYDEBITBQ"] = NulltoDecimal(TempBillSource.Compute("sum(FCURRENCYDEBIT)", a).ToString());
                    TempRow["FCURRENCYCREDITBQ"] = NulltoDecimal(TempBillSource.Compute("sum(FCURRENCYCREDIT)", a).ToString());
                    TempRow["FQUANTITYDEBITBQ"] = NulltoDecimal(TempBillSource.Compute("sum(FQUANTITYDEBIT)", a).ToString());
                    TempRow["FQUANTITYCREDITBQ"] = NulltoDecimal(TempBillSource.Compute("sum(FQUANTITYCREDIT)", a).ToString());
                }
                if (Key[3].ToString() == "1")
                {
                    TempRow["FDEBITAMOUNTQM"] = decimal.Parse(TempRow["FDEBITAMOUNTQC"].ToString()) + 
                        decimal.Parse(TempRow["FDEBITAMOUNTBQ"].ToString()) - 
                        decimal.Parse(TempRow["FCREDITAMOUNTBQ"].ToString());
                    TempRow["FCURRENCYDEBITQM"] = decimal.Parse(TempRow["FCURRENCYDEBITQC"].ToString()) + 
                        decimal.Parse(TempRow["FCURRENCYDEBITBQ"].ToString()) - 
                        decimal.Parse(TempRow["FCURRENCYCREDITBQ"].ToString());
                    TempRow["FQUANTITYDEBITQM"] = decimal.Parse(TempRow["FQUANTITYDEBITQC"].ToString()) + 
                        decimal.Parse(TempRow["FQUANTITYDEBITBQ"].ToString()) - 
                        decimal.Parse(TempRow["FQUANTITYCREDITBQ"].ToString());
                }
                else
                {
                    TempRow["FCREDITAMOUNTQM"] = decimal.Parse(TempRow["FCREDITAMOUNTQC"].ToString()) + 
                        decimal.Parse(TempRow["FCREDITAMOUNTBQ"].ToString()) - 
                        decimal.Parse(TempRow["FDEBITAMOUNTBQ"].ToString());
                    TempRow["FCURRENCYCREDITQM"] = decimal.Parse(TempRow["FCURRENCYCREDITQC"].ToString()) + 
                        decimal.Parse(TempRow["FCURRENCYCREDITBQ"].ToString()) - 
                        decimal.Parse(TempRow["FCURRENCYDEBITBQ"].ToString());
                    TempRow["FQUANTITYCREDITQM"] = decimal.Parse(TempRow["FQUANTITYCREDITQC"].ToString()) + 
                        decimal.Parse(TempRow["FQUANTITYCREDITBQ"].ToString()) - 
                        decimal.Parse(TempRow["FQUANTITYDEBITBQ"].ToString());
                }
                RestSource.Rows.Add(TempRow);
            }
            return;
        }

        private decimal NulltoDecimal(string Key)
        {
            if (StringUtils.IsEmpty(Key))
            {
                return decimal.Parse("0.000000");
            }
            return decimal.Parse(Key);
        }
        
    }
}
